package com.acoreful.acf2admin.modules.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;


@Component
@DependsOn("springContextHelper")
public class JobManage {
	
	private Logger logger=LoggerFactory.getLogger(JobManage.class);
	private static SchedulerFactoryBean schedulerFactoryBean;  
    private static Scheduler scheduler;
    
    static{  
        schedulerFactoryBean = (SchedulerFactoryBean) SpringContextHelper.getBeanByClass(SchedulerFactoryBean.class);
        scheduler = schedulerFactoryBean.getScheduler();
        
    }  
    /** 
     * 初始化定时任务 
     * @throws SchedulerException 
     */  
    public void initTask() throws SchedulerException { 
        //Scheduler scheduler = schedulerFactoryBean.getScheduler();  
        // 这里获取任务信息数据  
        /*List<ScheduleJob> jobList = timedTaskService.getAllJob();//从数据库中读取  
        for (ScheduleJob job : jobList) {  
            addJob(job);  
        } */
    }  
    /** 
     * 添加一个任务 
     * @param job 
     */  
    public void addJob(ScheduleJob job){  
        try {  
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());  
            // 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"  
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);  
            // 不存在，创建一个  
            if (null == trigger) {  
                JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)  
                        .withIdentity(job.getJobName(), job.getJobGroup()).build();  
                jobDetail.getJobDataMap().put("scheduleJob", job);  
                // 表达式调度构建器  
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());  
                // 按新的cronExpression表达式构建一个新的trigger  
                trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())  
                        .withSchedule(scheduleBuilder).build();  
                scheduler.scheduleJob(jobDetail, trigger);  
            } else {  
                // Trigger已存在，那么更新相应的定时设置  
                // 表达式调度构建器  
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());  
                // 按新的cronExpression表达式重新构建trigger  
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();  
                // 按新的trigger重新设置job执行  
                scheduler.rescheduleJob(triggerKey, trigger);  
            }  
            if(job.getJobStatus()==0){  
                pauseJob(job);  
            }  
              
        } catch (SchedulerException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
    /** 
     * 暂停一个job 
     * @param scheduleJob 
     * @throws SchedulerException 
     */  
    public void pauseJob(ScheduleJob scheduleJob){  
        //Scheduler scheduler = schedulerFactoryBean.getScheduler();  
        logger.info(scheduleJob.getJobName(),"定时任务暂停");  
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());  
        try {  
            scheduler.pauseJob(jobKey);  
        } catch (SchedulerException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
    /** 
     * 恢复一个job 
     * @param scheduleJob 
     */  
    public void resumeJob(ScheduleJob scheduleJob){  
        logger.info(scheduleJob.getJobName(),"定时任务启动");  
        //Scheduler scheduler = schedulerFactoryBean.getScheduler();  
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(),scheduleJob.getJobGroup());  
        try {  
            scheduler.resumeJob(jobKey);  
        } catch (SchedulerException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
    /** 
     * 删除一个任务 
     * @param scheduleJob 
     */  
    public void removeJob(ScheduleJob job){  
        logger.info(job.getJobName(),"删除定时任务");  
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());  
        JobKey jobKey = JobKey.jobKey(job.getJobName(),job.getJobGroup());  
        // 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"  
        //CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);  
        try {  
            scheduler.pauseTrigger(triggerKey);  
            scheduler.unscheduleJob(triggerKey);  
            scheduler.deleteJob(jobKey);  
        } catch (SchedulerException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
}
